package com.jt.www.admin.order_pc.controller;

import com.jt.www.admin.order_pc.service.InsPreRecordService;
import com.jt.www.model.insprerecord.InsPreRecordEntity;
import com.jt.www.model.insprerecord.vo.InsPreParamVO;
import com.jt.www.model.insprerecord.vo.InsPreRecordExportVO;
import com.jt.www.model.remote.user.LoginResultVO;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.remote.UserClient;
import com.jt.www.util.JsonUtil;
import com.jt.www.util.excel.CsvExportUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author admin_ltf
 * @create 2019-05-10 11:53
 */
@Api(value = "预录", tags = {"INS-PRE-RECORD-API"}, description = "预录")
@RestController
@RequestMapping(value = "/ins/pre")
public class InsPreRecordController {

    public static final Logger log = LoggerFactory.getLogger(InsPreRecordController.class);
    private final static String SYS_EDU_PC_CODE = "sys_edu_pc";
    @Autowired
    private InsPreRecordService insPreRecordService;
    @Autowired
    private UserClient userClient;

    /**
     * 增加预录信息
     *
     * @param insPreRecordEntities
     * @return
     */
    @ApiOperation(value = "增加预录信息", notes = "增加预录信息", httpMethod = "POST")
    @PostMapping(value = "/add")
    public ResponseEntity insertPreRecordInfo(@RequestBody List<InsPreRecordEntity> insPreRecordEntities) {
        Integer num = insPreRecordService.addPreRecordInfo(insPreRecordEntities);
        if (num == insPreRecordEntities.size()) {
            return GenericDataResponse.ok();
        } else if (num == -1) {
            return GenericDataResponse.errorWithMsg("参数不能为空");
        }
        return GenericDataResponse.errorWithMsg("添加失败");
    }


    /**
     * 修改预录信息
     *
     * @param insPreRecordEntity
     * @return
     */
    @ApiOperation(value = "修改预录信息", notes = "修改预录信息", httpMethod = "POST")
    @PostMapping(value = "/update")
    public ResponseEntity updatePreRecordInfo(@RequestBody InsPreRecordEntity insPreRecordEntity) {

        Integer num = insPreRecordService.updatePreRecordInfo(insPreRecordEntity);
        if (num == 1) {
            return GenericDataResponse.ok();
        } else if (num == -1) {
            return GenericDataResponse.errorWithMsg("参数不能为空");
        }
        return GenericDataResponse.errorWithMsg("修改失败");
    }

    /**
     * 修改预录信息状态
     *
     * @param id
     * @param status
     * @return
     */
    @ApiOperation(value = "修改预录信息状态", notes = "修改预录信息状态", httpMethod = "GET")
    @GetMapping(value = "/updateStatus")
    public ResponseEntity updatePreRecordStatus(@ApiParam(value = "id", required = true) @RequestParam("id") String id, @ApiParam(value = "状态： 1已保存 2已提交 3删除", required = true) @RequestParam("status") String status) {

        if (StringUtils.isEmpty(id)) {
            log.error("【修改预录信息状态】id为空");
            return GenericDataResponse.errorWithMsg("参数不能为空");
        }

        if (StringUtils.isEmpty(status)) {
            log.error("【修改预录信息状态】status为空");
            return GenericDataResponse.errorWithMsg("参数不能为空");
        }
        Integer num = insPreRecordService.updatePreRecordStatus(id, status);
        if (num == 1) {
            return GenericDataResponse.ok();
        }
        return GenericDataResponse.errorWithMsg("修改状态失败");
    }

    /**
     * 根据创建人usercode或被保险人usercode查询预录信息(业务端使用)
     *
     * @param userCode
     * @param isNeedContent
     * @param page
     * @param rows
     * @return
     */
    @ApiOperation(value = "根据创建人usercode或投保人usercode查询预录信息(业务端使用)", notes = "根据创建人usercode或投保人usercode查询预录信息(业务端使用)", httpMethod = "GET")
    @GetMapping(value = "/getInfoByCode", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity searchPreRecordByCode(@ApiParam(value = "创建人usercode", required = true) @RequestParam("userCode") String userCode,
                                                @ApiParam(value = "保险产品", required = false) @RequestParam(value = "productName", required = false) String productName,
                                                @ApiParam(value = "是否需要内容,需要内容传1，不需要内容不传即可", required = false) @RequestParam(value = "isNeedContent", required = false) String isNeedContent,
                                                @ApiParam(value = "分页参数，第几页", required = true) @RequestParam(value = "page", defaultValue = "1") Integer page,
                                                @ApiParam(value = "分页参数，每页显示条数", required = true) @RequestParam(value = "rows", defaultValue = "10") Integer rows) {

        if (StringUtils.isEmpty(userCode)) {
            log.error("【根据创建人usercode或投保人usercode查询预录信息】userCode为空");
            return GenericDataResponse.errorWithMsg("参数不能为空");
        }

        HashMap<String, Object> resultMap = insPreRecordService.searchInfoByCode(userCode, productName, isNeedContent, page, rows);
        return GenericDataResponse.okWithData(resultMap);
    }


    /**
     * 根据id查询预录详情信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询预录详情信息", notes = "根据id查询预录详情信息", httpMethod = "GET")
    @GetMapping(value = "/getSingleInfoById")
    public ResponseEntity searchSingleInfo(@ApiParam(value = "预录信息id", required = true) @RequestParam("id") String id) {
        if (StringUtils.isEmpty(id)) {
            log.error("【根据id查询预录详情信息】id为空");
            return GenericDataResponse.errorWithMsg("参数不能为空");
        }
        InsPreRecordEntity resultEntity = insPreRecordService.searchSingleInfo(id);
        return GenericDataResponse.okWithData(resultEntity);
    }

    /**
     * 条件查询预录信息(管理端使用)
     *
     * @return
     */
    @ApiOperation(value = "条件查询预录信息(管理端使用)", notes = "条件查询预录信息(管理端使用)", httpMethod = "POST")
    @PostMapping(value = "/getInfoByCode")
    public ResponseEntity searchPreRecordInfo(@RequestBody InsPreParamVO insPreParamVO) {


        HashMap<String, Object> resultMap = insPreRecordService.searchPreRecordInfo(insPreParamVO);


        return GenericDataResponse.okWithData(resultMap);
    }

    @ApiOperation(value = "导出预录信息列表", notes = "导出预录信息列表")
    @GetMapping(value = "/exportList", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void exportList(InsPreParamVO insPreParamVO, HttpServletResponse response, HttpServletRequest request) {
        String findCode = "insPre_exportList_" + System.currentTimeMillis();

        try {

            log.info("{} 导出预录列表 入参：insPreParamVO->{}", findCode, JsonUtil.object2Json(insPreParamVO));

            // 查询需要导出的数据
            List<InsPreRecordExportVO> list = insPreRecordService.exportList(insPreParamVO);

            // 构造导出数据结构
            String titles = "预录单号,产品名称,投保人名称,被保险人名称,保费,投保人登录账号,省,市,区";  // 设置表头
            String keys = "id,productName,userName,insuredName,premiumTotal,loginAccount,proName,cityName,countryName";  // 设置每列字段

            // 构造导出数据
            List<Map<String, Object>> datas = new ArrayList<>();
            Map<String, Object> map = null;

            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {

                    map = new HashMap<>();
                    map.put("id", list.get(i).getId());
                    map.put("productName", list.get(i).getProductName());
                    map.put("userName", list.get(i).getUserName());
                    map.put("insuredName", list.get(i).getInsuredName());
                    map.put("premiumTotal", StringUtils.isEmpty(list.get(i).getPremiumTotal()) ? "" : list.get(i).getPremiumTotal());

                    log.info("{} 导出预录 预录单号: {} 投保人userCode: {}", findCode, list.get(i).getId(), list.get(i).getUserCode());
                    ResponseEntity<GenericDataResponse<LoginResultVO>> userResponse = userClient.queryInfoByUserCode(list.get(i).getUserCode(), SYS_EDU_PC_CODE);
                    log.info("{} 导出预录 预录单号: {} 根据投保人userCode查询登录账号结果: {}", findCode, list.get(i).getId(), JsonUtil.object2Json(userResponse));
                    if (null != userResponse && null != userResponse.getBody()) {
                        LoginResultVO userInfo = userResponse.getBody().getData();
                        map.put("loginAccount", StringUtils.isEmpty(userInfo.getLoginAccount()) ? "" : userInfo.getLoginAccount());
                    } else {
                        map.put("loginAccount", "");
                    }

                    map.put("proName", list.get(i).getProName());
                    map.put("cityName", list.get(i).getCityName());
                    map.put("countryName", list.get(i).getCountryName());

                    datas.add(map);
                }
            }

            // 设置导出文件前缀
            String fName = "预录信息_";

            // 文件导出
            OutputStream os = response.getOutputStream();
            CsvExportUtil.responseSetProperties(fName, response);
            CsvExportUtil.doExport(datas, titles, keys, os);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("{} 预录信息 导出失败 {}", findCode, e);
        }
    }

}
